package org.gruposp2p.dnie.ui.dialogs;

import dniegp2pclient.DNIeGP2PClientApp;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.gruposp2p.dnie.crypto.SignatureValidator;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;

/**
 *
 * @author jj
 */
public class SignedDocumentDialog extends javax.swing.JDialog {

    private ResourceMap resourceMap;
    private X509Certificate cert;
    private String separador = System.getProperty("line.separator");
    private String xmlSignedData;
    
    /** Creates new form SignedFileDialog */
    public SignedDocumentDialog(java.awt.Frame parent, boolean modal,
            String xmlSignedData) {
        super(parent, modal);
        this.xmlSignedData = xmlSignedData;
        resourceMap = Application.getInstance(DNIeGP2PClientApp.class)
                .getContext().getResourceMap(SignedDocumentDialog.class);
        setTitle(resourceMap.getString("title"));
        this.setLocationRelativeTo(parent);
        try {
            SignatureValidator signatureValidator = new SignatureValidator();
            signatureValidator.validateSignature(xmlSignedData, false);
            cert = signatureValidator.getCertificate();
            initComponents();
            X500Principal x500Principal = cert.getSubjectX500Principal();
            signerData.setText(splitStringConSeparador(x500Principal.toString()));
            X500Principal x500IssuerPrincipal = cert.getIssuerX500Principal();
            CAData.setText(splitStringConSeparador(x500IssuerPrincipal.toString()));
        } catch (Exception ex) {
            Logger.getLogger(SignedDocumentDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        filePanel = new javax.swing.JPanel();
        validationResultLabel = new javax.swing.JLabel();
        fileTypeLabel = new javax.swing.JLabel();
        fileTypeCaptionLabel = new javax.swing.JLabel();
        scrollPaneSignerData = new javax.swing.JScrollPane();
        signerData = new javax.swing.JEditorPane();
        scrollPaneCA = new javax.swing.JScrollPane();
        CAData = new javax.swing.JEditorPane();
        closeButton = new javax.swing.JButton();
        viewDocumentButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        filePanel.setName("filePanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(DNIeGP2PClientApp.class).getContext().getResourceMap(SignedDocumentDialog.class);

        validationResultLabel.setFont(new java.awt.Font("DejaVu Sans", 1, 15));
        validationResultLabel.setText(resourceMap.getString("validationOkText.text"));
        validationResultLabel.setName("validationResultLabel"); // NOI18N

        fileTypeLabel.setFont(new java.awt.Font("DejaVu Sans", 1, 15));
        fileTypeLabel.setText(resourceMap.getString("userSignedFileType.text"));
        fileTypeLabel.setName("fileTypeLabel"); // NOI18N

        fileTypeCaptionLabel.setText(resourceMap.getString("documentType.text"));
        fileTypeCaptionLabel.setName("fileTypeCaptionLabel"); // NOI18N

        scrollPaneSignerData.setBackground(new java.awt.Color(237, 236, 235));
        scrollPaneSignerData.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("signerData.text")));
        scrollPaneSignerData.setName("scrollPaneSignerData"); // NOI18N

        signerData.setBackground(new java.awt.Color(255, 255, 255));
        signerData.setBorder(null);
        signerData.setEditable(false);
        signerData.setName("signerData"); // NOI18N
        scrollPaneSignerData.setViewportView(signerData);

        scrollPaneCA.setBackground(new java.awt.Color(237, 236, 235));
        scrollPaneCA.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("caDataText.text")));
        scrollPaneCA.setName("scrollPaneCA"); // NOI18N

        CAData.setBackground(new java.awt.Color(255, 255, 255));
        CAData.setBorder(null);
        CAData.setEditable(false);
        CAData.setName("CAData"); // NOI18N
        this.resourceMap = resourceMap;
        scrollPaneCA.setViewportView(CAData);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(SignedDocumentDialog.class, this);
        closeButton.setAction(actionMap.get("closePanel")); // NOI18N
        closeButton.setIcon(resourceMap.getIcon("cancelIcon.icon")); // NOI18N
        closeButton.setText(resourceMap.getString("closeText.text"));
        closeButton.setName("closeButton"); // NOI18N

        viewDocumentButton.setAction(actionMap.get("viewDocument")); // NOI18N
        viewDocumentButton.setIcon(resourceMap.getIcon("certIcon.icon")); // NOI18N
        viewDocumentButton.setText(resourceMap.getString("viewDocument.text"));
        viewDocumentButton.setName("viewDocumentButton"); // NOI18N

        javax.swing.GroupLayout filePanelLayout = new javax.swing.GroupLayout(filePanel);
        filePanel.setLayout(filePanelLayout);
        filePanelLayout.setHorizontalGroup(
            filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(filePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPaneSignerData, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(filePanelLayout.createSequentialGroup()
                        .addComponent(validationResultLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                        .addComponent(fileTypeCaptionLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fileTypeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(scrollPaneCA, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, filePanelLayout.createSequentialGroup()
                        .addComponent(viewDocumentButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(closeButton)))
                .addContainerGap())
        );
        filePanelLayout.setVerticalGroup(
            filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(filePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(validationResultLabel)
                    .addComponent(fileTypeLabel)
                    .addComponent(fileTypeCaptionLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollPaneCA, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollPaneSignerData, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(filePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(closeButton)
                    .addComponent(viewDocumentButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(filePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(filePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SignedDocumentDialog dialog = new SignedDocumentDialog(
                        new javax.swing.JFrame(), true, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    @Action
    public void closePanel() {
        this.dispose();
    }

    private String splitStringConSeparador (String cadena) {
        String[] temp = cadena.split(", ");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < temp.length; i++) {
            sb.append(temp[i] + separador);
        }
        return sb.toString();
    }

    @Action
    public void viewDocument() {
        SignedFilesViewerDialog signedFilesViewer =
                new SignedFilesViewerDialog (
                DNIeGP2PClientApp.getApplication().getView().getFrame(), true, xmlSignedData);
        signedFilesViewer.setVisible(true);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JEditorPane CAData;
    private javax.swing.JButton closeButton;
    private javax.swing.JPanel filePanel;
    private javax.swing.JLabel fileTypeCaptionLabel;
    private javax.swing.JLabel fileTypeLabel;
    private javax.swing.JScrollPane scrollPaneCA;
    private javax.swing.JScrollPane scrollPaneSignerData;
    private javax.swing.JEditorPane signerData;
    private javax.swing.JLabel validationResultLabel;
    private javax.swing.JButton viewDocumentButton;
    // End of variables declaration//GEN-END:variables

}
